package app;

import java.io.IOException;
import java.util.Vector;

import lib.Payload;
import lib.Symbols;
import core.CausalHandler;
import core.MessageListener;

public class ChatHandler extends Thread implements MessageListener {
	
	private CausalHandler causalhandler;
	private ChatGUI chatGUI;
	private String nickName;
	private boolean logoff;
	
	public ChatHandler() throws IOException {
		this.causalhandler = new CausalHandler(this, Symbols.GROUP_IP, Symbols.CHAT_PORT, Symbols.TTL);
		this.chatGUI = new ChatGUI(this);
		this.logoff = false;
	}
	
	public String getNickName() {
		return nickName;
	}
	
	public void showGUI() {
		chatGUI.initialize();
	}
	
	public void logon(String nickName) throws IOException {
		this.nickName = nickName;
		this.start();
		causalhandler.logon(nickName);
	}
	
	public void logoff() throws IOException {
		logoff = true;
		causalhandler.logoff();
	}

	public void pushMessages(Vector<Payload> payloads) {
		if(payloads!=null && !payloads.isEmpty()) {
			for(Payload payload : payloads) {
				ChatPayload chatPayload = (ChatPayload) payload;
				chatGUI.appendMessage(chatPayload);
			}
		}
	}
	
	public void listen() throws IOException {
		ChatPayload chatPayload = (ChatPayload) causalhandler.receiveMessage(Symbols.MAX_BUFFER_DIM);
		if(chatPayload!=null) {
			chatGUI.appendMessage(chatPayload);
		}
	}
	
	public void broadcast(String author, String text) throws IOException {
		ChatPayload payload = new ChatPayload(author, text);
		causalhandler.sendMessage(payload);
	}
	
	public void run() {
		while(!logoff) {
			try {
				listen();
				if(Math.random()<Symbols.DELAY_PROB) {
					long ms = (long)Math.ceil(Math.random()*Symbols.MAX_DELAY)*1000;
					if(ms>500) {
						// sleep only for more than half second
						Thread.sleep(ms);
					}
				}
			} catch (IOException e) {
				//e.printStackTrace();
			} catch (InterruptedException e) {
				//e.printStackTrace();
			}
		}
	}
	
}
